﻿using System;
using System.IO;
using Microsoft.Win32;
using Microsoft.MediaPlayer.Interop;
using BMproductions.Media.MediaPlayer.WMPPlus.Properties;

namespace BMproductions.Media.MediaPlayer.WMPPlus {
	public class WMPPlugin {
		internal IntPtr Native { get; set; }

		internal PluginManager manager;

		public bool HasPlugin {
			get { return Native != IntPtr.Zero; }
		}

		public Guid CLSID { get; private set; }
		string label;
		public string Label { get { return this.label; } }
		string library;
		public int Capabilities { get; private set; }
		public bool Loaded { get; internal set; }
		bool resource;
		public IWMPPluginUI Original { get; internal set; }
		public string KeyPath { get; private set; }

		static string GetInprocServer(Guid clsid) {
			var root = Registry.ClassesRoot;
			using (var key = root.OpenSubKey(String.Format(@"CLSID\{0:B}\InprocServer32", clsid), false)) {
				return WMPPlusSettings.LoadRegistryString(key, null, null);
			}
		}
	
		public WMPPlugin(PluginManager manager, Guid clsid) {
			this.manager = manager;
			Loaded = false;
			CLSID = clsid;
			KeyPath = Path.Combine(WMPConstants.PLUGIN_INSTALLREGKEY, clsid.ToString("B"));
			LoadRegistry();
		}

		void LoadRegistry() {
			this.library = GetInprocServer(CLSID);
			var root = Registry.LocalMachine;
			using(var key = root.OpenSubKey(KeyPath, false)) {
				if (key == null) return;
				this.label = WMPPlusSettings.LoadRegistryString(key, WMPConstants.PLUGIN_INSTALLREGKEY_FRIENDLYNAME, null);
				string reslib;
				if (!WMPPlusHookData.ResolveLabel(ref this.label, this.library, out reslib) || this.label == null)
					this.label = Resources.UnknownFriendlyName;
				if (String.Compare("wmploc.dll", reslib) == 0) {
					this.resource = true;
					this.library = "wmploc.dll";
				} else {
					try {
						this.resource = !this.library.IsNullEmpty() &&
							(File.GetAttributes(this.library) & FileAttributes.Directory) != FileAttributes.Directory;
					}
					catch {
						this.resource = false;
					}
				}
				Capabilities = WMPPlusSettings.LoadRegistryNumber(key, WMPConstants.PLUGIN_INSTALLREGKEY_CAPABILITIES, 0);
			}
		}
	
		bool GetRunning() {
			var root = Registry.CurrentUser;
			using(var key = root.OpenSubKey(KeyPath)) {
				return WMPPlusSettings.LoadRegistryBool(key, "Running", false);
			}
		}
	}
}
